package sdk.webview.fmc.com.fmcsdk.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import sdk.webview.fmc.com.fmcsdk.db.Record.Sync;

/**
 * 数据库管理类
 *
 */
public class ADBManager {
	
	SQLiteOpenHelper dbHelper;
	SQLiteDatabase db;

	public ADBManager(SQLiteOpenHelper helper){
		dbHelper = helper;
		try {
			if(dbHelper==null)return;
			db = dbHelper.getWritableDatabase();
		}catch (Exception e){}


	}
	
	/**
	 * 执行SQL
	 * 
	 * @param sql
	 *            SQL语句
	 */
	public void execSQL(String sql) {
		getWriteableDatabase();
		db.execSQL(sql);
	}
	/**
	 * 在同一事务中执行多条sql语句
	 * @param sqls
	 */
	public void execSqlsInTransition(String[] sqls) throws Exception {
		if (sqls==null||sqls.length==0) {
			return ;
		}
		getWriteableDatabase();
		try {
			db.beginTransaction();
			for (String sql : sqls) {
				db.execSQL(sql);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {

			throw e;
		}finally{
			db.endTransaction();
		}

	}
	/**
	 * 获取可读写数据库
	 */
	private void getWriteableDatabase() {
		db = dbHelper.getWritableDatabase();
	}
	
	/**
	 * 获取只读数据库
	 */
	private synchronized void getReadableDatabase(){
		db = dbHelper.getReadableDatabase();
	}
	
	
	public void execSQL(String sql, Object[] bindArgs){
		getWriteableDatabase();
		db.execSQL(sql, bindArgs);
	}

	/**
	 * 插入新数据
	 * 
	 * @param table
	 * @param values
	 */
	public long insert(String table, ContentValues values) {
		getWriteableDatabase();
		return db.insert(table, null, values);
	}

	/**
	 * 向指定表中插入多条Record数据
	 * 
	 * @param records
	 */
	public void insert(List<Record> records) {
		getWriteableDatabase();
		for (Record record : records) {
			insert(record);
		}
	}

	/**
	 * 插入Record数据
	 * 
	 * @param record
	 */
	public void insert(Record record) {
		getWriteableDatabase();
		String table = record.getTable();
		Iterator<String> iter = record.getFields().iterator();
		// 生成主表的contentValues数据
		ContentValues values = new ContentValues();
		// 填充主数据
		while (iter.hasNext()) {
			String field = iter.next();
			String value = record.getString(field);
			values.put(field, value);
		}
		values.put(Table.SYNC, record.getSyncState().toString());
		long id=0;
		try {
			// 插入主表的数据
			id = insert(table, values);
		} catch(Exception exception){
			exception.printStackTrace();

		}finally{
		}
		record.setValue("_id", id);
	}

	/**
	 * 获取单条记录
	 * 
	 * @param table
	 * @param where
	 * @return
	 */
	public Record getRecord(String table, String where) {
		Record record = new Record(table);
		Sync syncstate = Sync.SYNC;
		String sql = "select * from " + table;
		if(!where.isEmpty())
		  sql += " where " + where;
		Cursor cursor = null;
		try {
			getReadableDatabase();
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToFirst()) {
				int count = cursor.getColumnCount();
				for (int i = 0; i < count; i++) {
					String field = cursor.getColumnName(i);
					String value = cursor.getString(i);
					//如果是记录状态信息，保存下来最后进行设置 
					if(field.equals(Table.SYNC)){
						syncstate = Sync.valueOf(value);
						continue;
					}
					record.setValue(field, value);
				}
				//设置记录状态
				record.setSyncState(syncstate);
				record.setChanged(false);
				return record;
			}else{
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();

			return null;
		}finally{
			if(cursor != null){
				cursor.close();
			}
		}
	}

	/**
	 * 获取多条记录
	 * 
	 * @param table
	 * @param where
	 * @return
	 */
	public List<Record> getRecords(String table, String where) {
		List<Record> list = new ArrayList<Record>();
		String sql = "select distinct * from " + table;
		if(where !=null && !where.isEmpty())
		  sql += " where " + where;
		Cursor cursor=null;
		try {
			getReadableDatabase();
			cursor = db.rawQuery(sql, null);
			int count = cursor.getColumnCount();
			while (cursor.moveToNext()) {
				Record record = new Record(table);
				Sync syncstate = Sync.SYNC;
				for (int i = 0; i < count; i++) {
					String field = cursor.getColumnName(i);
					String value = cursor.getString(i);
					//如果是记录状态信息，保存下来最后进行设置 
					if(field.equals(Table.SYNC)){
						syncstate = Sync.valueOf(value);
						continue;
					}
					record.setValue(field, value);
				}
				//设置记录状态
				record.setSyncState(syncstate);
				//设置为未修改状态
				record.setChanged(false);
				list.add(record);
			}
		} catch (Exception e) {
			e.printStackTrace();

		}finally{
			if(cursor != null)
				cursor.close();
		}
		return list;
	}
	
	/**
	 * 带删除重复记录,根据表的表名加ID
	 * @param table
	 * @param where
	 * @param b
	 * @return
	 */
	public List<Record> getRecords(String table, String where, boolean b) {
		return getRecords(table, where, b, table+"id");
	}
	
	/**
	 * 带删除重复记录
	 * @param table
	 * @param where
	 * @param b
	 * @return
	 */
	public List<Record> getRecords(String table, String where, boolean b, String groupbyteWhere) {
		getReadableDatabase();
		db.beginTransaction();
		if(b){
			String s="delete from "+table+" where _id not in (select max(_id) from "+table+" group by "+groupbyteWhere+")";
			db.execSQL(s);
		}
		List<Record> list = new ArrayList<Record>();
		String sql = "select distinct * from " + table;
		if(where !=null && !where.isEmpty())
		  sql += " where " + where;
		Cursor cursor=null;
		try {
			cursor = db.rawQuery(sql, null);
			int count = cursor.getColumnCount();
			while (cursor.moveToNext()) {
				Record record = new Record(table);
				Sync syncstate = Sync.SYNC;
				for (int i = 0; i < count; i++) {
					String field = cursor.getColumnName(i);
					String value = cursor.getString(i);
					//如果是记录状态信息，保存下来最后进行设置 
					if(field.equals(Table.SYNC)){
						syncstate = Sync.valueOf(value);
						continue;
					}
					record.setValue(field, value);
				}
				//设置记录状态
				record.setSyncState(syncstate);
				//设置为未修改状态
				record.setChanged(false);
				list.add(record);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();

		}finally{
			if(cursor != null)
				cursor.close();
			db.endTransaction();
		}
		return list;
	}
	
	
	
	/**
	 * 查询多个字段值
	 * @param table 表名
	 * @param fields 字段名集合
	 * @param where 查询条件
	 * @return
	 */
	public Map<String, String> getValues(String table, String[] fields, String where){
		Map<String, String> data = new HashMap<String, String>();
		StringBuffer sb = new StringBuffer("select ");
		for(String field:fields){
			sb.append(field).append(",");
		}
		//减去最后一个","
		sb.replace(sb.length()-1, sb.length(), "");
		sb.append(" from ").append(table);
		if(where != null && where.length()>0 ){
			sb.append(" where ").append(where);
		}
		
		Cursor cursor = null;
		try {
			cursor = rawQuery(sb.toString(), null);
			if(cursor.moveToFirst()){
				for(int i = 0;i<fields.length;i++){
					String field = fields[i];
					String value = cursor.getString(i);
					data.put(field, value);
				}
			}
		}catch (Exception e){
			e.printStackTrace();

		}finally{
			if(cursor != null)
				cursor.close();
		}
		
		return data;
	}
	
	public List<Map<String, String>> getValuesList(String table, String[] fields, String where){
		List<Map<String, String>> datas=new ArrayList<Map<String,String>>();
		StringBuffer sb = new StringBuffer("select distinct ");
		for(String field:fields){
			sb.append(field).append(",");
		}
		//减去最后一个","
		sb.replace(sb.length()-1, sb.length(), "");
		sb.append(" from ").append(table);
		if(where != null && where.length()>0 ){
			sb.append(" where ").append(where);
		}
		
		Cursor cursor = null;
		try {
			cursor = rawQuery(sb.toString(), null);
			while(cursor.moveToNext()){
				Map<String, String> data = new HashMap<String, String>();
				for(int i = 0;i<fields.length;i++){
					String field = fields[i];
					String value = cursor.getString(i);
					data.put(field, value);
				}
				datas.add(data);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			if(cursor != null)
				cursor.close();
		}
		
		return datas;
	}
	
	/**
	 * 查询指定字段
	 * @param table 表名
	 * @param field 字段名
	 * @param where 查询条件
	 * @return 
	 */
	public String getValue(String table, String field, String where){
		String value = "";
		String sql = "select "+field+" from "+table+" where "+where;
		Cursor cursor = null;
		try {
			cursor = rawQuery(sql, null);
			if(cursor.moveToFirst()){
				value = cursor.getString(0);
			}
		}catch(Exception e){

			return "";
		}finally{
			if(cursor != null)
				cursor.close();
		}
		return value;
	}

	/**
	 * 删除多条记录
	 * @param records
	 */
	public void deleteRecords(List<Record> records) {
		if(records == null || records.size() == 0)
			return;
		getWriteableDatabase();
		db.beginTransaction();
		try {
			for (Record record:records) {
				delete(record);
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			e.printStackTrace();

		}finally{
			db.endTransaction();
		}
	}

	/**
	 * 删除指定的Record记录
	 * 
	 * @param record
	 */
	public void delete(Record record) {
		getWriteableDatabase();
		String table = record.getTable();
		String _id = record.getString("_id");
		if (_id.isEmpty()) {
			return;
		}
		delete(table, "_id=?", new String[]{_id});
	}

	/**
	 * 删除数据
	 * 
	 * @param table
	 * @param whereClause
	 * @param whereArgs
	 */
	public void delete(String table, String whereClause, String[] whereArgs) {
		getWriteableDatabase();
		db.delete(table, whereClause, whereArgs);
	}

	/**
	 * 根据_id进行更新
	 * @param record
	 */
	public void updateById(Record record) {
		getWriteableDatabase();
		if(record != null){
			String _id = record.getString("_id");
			update(record, "_id=?", new String[]{_id});
		}
	}
	
	/**
	 * 批量更新
	 * @param records
	 */
	public void updateRecords(List<Record> records){
		getWriteableDatabase();
		for(Record record:records){
			updateById(record);
		}
	}
	
	/**
	 * 根据条件进行更新
	 * @param record
	 * @param whereClause
	 * @param whereArgs
	 */
	public void update(Record record, String whereClause, String[] whereArgs) {
		getWriteableDatabase();
		String table = record.getTable();
		String sql = "select * from " + table;
		if(!whereClause.isEmpty())
		  sql += " where " + whereClause;
		Cursor cursor = null;
		try {
			getWriteableDatabase();
			cursor= db.rawQuery(sql, whereArgs);
			//查询数据库中没有相关数据，则插入该条数据，否则更新
			if(cursor.getCount() == 0){
				insert(record);
			}else{
				//修改过才进行更新
				if(record.isChanged()){
					ContentValues values = new ContentValues();
					Iterator<String> iter = record.getFields().iterator();
					while (iter.hasNext()) {
						String field = iter.next();
						String value = record.getString(field);
						if (value != null) {
							values.put(field, value);
						}
					}
					update(table, values, whereClause, whereArgs);
				}
			}
		}catch (Exception e){
			e.printStackTrace();

		}
		finally{
			if(cursor != null)
				cursor.close();
		}
	}

	/**
	 * 更新数据
	 * 
	 * @param table
	 * @param values
	 * @param whereClause
	 * @param whereArgs
	 */
	public int update(String table, ContentValues values, String whereClause,
                      String[] whereArgs) {
		getWriteableDatabase();
		int rows = db.update(table, values, whereClause, whereArgs);
		return rows;
	}
	
	/**
	 * 是否包含某条记录
	 * @return
	 */
	public boolean contain(String table, String where){
		boolean b=false;
		String sql;
		if(TextUtils.isEmpty(where)){
			sql="select count(1) from "+table;
		}else {
			sql="select count(1) from "+table+" where "+where;
		}
		Cursor c=db.rawQuery(sql,null);
		if(c.moveToNext()&&c.getInt(0)>0){
			b=true;
		}
		c.close();
		return b;
	}
	
	
	public Cursor rawQuery(String sql, String[] selectionArgs) {
		getWriteableDatabase();
		Cursor c = db.rawQuery(sql, selectionArgs);
		return c;
	}
	
	public void close(){
		db.close();
	}
	
	public SQLiteDatabase getDB(){
		getWriteableDatabase();
		return db;
	}



}
